package dk.modified.reshary;

import java.util.Map;

import org.apache.http.Header;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.plus.Plus;
import com.google.android.gms.plus.model.people.Person;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.sromku.simple.fb.Permission;
import com.sromku.simple.fb.Permission.Type;
import com.sromku.simple.fb.SimpleFacebook;
import com.sromku.simple.fb.SimpleFacebookConfiguration;
import com.sromku.simple.fb.entities.Profile;
import com.sromku.simple.fb.listeners.OnLoginListener;
import com.sromku.simple.fb.listeners.OnProfileListener;

import dk.modified.reshary.GlobalState.TrackerName;

public class LoginOrSignup extends Activity implements ConnectionCallbacks,
		OnConnectionFailedListener {

	private GoogleApiClient mGoogleApiClient;
	private Boolean mIntentInProgress = false;
	private final int RC_SIGN_IN = 1337;
	private final int RESULT_OK = -1;

	private SimpleFacebook mSimpleFacebook;

	private OnLoginListener onLoginListener;

	private Button cmd_facebook_signup;

	// private LoginButton authButton;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Tracker t = ((GlobalState) getApplication())
				.getTracker(TrackerName.APP_TRACKER);
		t.setScreenName("Reshary LoginOrSignup");
		t.send(new HitBuilders.AppViewBuilder().build());
		SharedPreferences sharedpreferences = getSharedPreferences(
				"dk.modified.reshary", Context.MODE_PRIVATE);
		String userid = sharedpreferences.getString("userid", "null");
		String securitytoken = sharedpreferences.getString("securitytoken",
				"null");
		if (!userid.equals("null") && (!securitytoken.equals("null"))) {
			Intent loggedin = new Intent(getApplicationContext(),
					MainActivity.class);
			loggedin.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
					| Intent.FLAG_ACTIVITY_CLEAR_TASK);
			startActivity(loggedin);
		}
		setContentView(R.layout.activity_login_or_signup);
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			if (extras.getString("failure") != null) {
				Toast.makeText(getApplicationContext(),
						extras.getString("failure"), Toast.LENGTH_LONG).show();
			}
		}

		cmd_facebook_signup = (Button) findViewById(R.id.cmd_facebook_signup);
		cmd_facebook_signup.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mSimpleFacebook.login(onLoginListener);
			}
		});


		Permission[] permissions = new Permission[] { Permission.EMAIL,
				Permission.PUBLIC_PROFILE, Permission.USER_FRIENDS };

		SimpleFacebookConfiguration configuration = new SimpleFacebookConfiguration.Builder()
				.setAppId("1388839554693945")
				.setNamespace("dk_modified_reshary")
				.setPermissions(permissions).build();

		SimpleFacebook.setConfiguration(configuration);

		onLoginListener = new OnLoginListener() {

			@Override
			public void onFail(String arg0) {
				// TODO Auto-generated method stub
				if (arg0 != null) {
					Log.d("onFail", arg0);
				} else {
					Log.d("onFail", "No Message");
				}

			}

			@Override
			public void onException(Throwable arg0) {
				// TODO Auto-generated method stub
				if (arg0 != null) {
					Toast.makeText(getApplicationContext(), arg0.getMessage(), Toast.LENGTH_LONG).show();
				} else {
					Log.d("onException", "No Message");
				}
			}

			@Override
			public void onThinking() {
				// TODO Auto-generated method stub
				Log.d("onThinking", "No Message");
			}

			@Override
			public void onNotAcceptingPermissions(Type arg0) {
				// TODO Auto-generated method stub
				Log.d("onNotAcceptingPermissions", "TEST");
			}

			@Override
			public void onLogin() {
				mSimpleFacebook.getProfile(new OnProfileListener() {

					@Override
					public void onComplete(Profile response) {
						// TODO Auto-generated method stub
						super.onComplete(response);
						PostSignupWithFacebook(response);
					}
					
					
				});
			}
		};

		mGoogleApiClient = new GoogleApiClient.Builder(this)
				.addConnectionCallbacks(this)
				.addOnConnectionFailedListener(this).addApi(Plus.API)
				.addScope(Plus.SCOPE_PLUS_PROFILE).build();

	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onStop() {
		super.onStop();
		if (mGoogleApiClient.isConnected()) {
			mGoogleApiClient.disconnect();
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		Log.d("TEST", "CALLED");
		
		
		if (requestCode == RC_SIGN_IN) {
			mIntentInProgress = false;
			if (resultCode == RESULT_OK) {

				if (!mGoogleApiClient.isConnecting()) {
					mGoogleApiClient.connect();
				}
			} else {
				if (mGoogleApiClient.isConnected()
						|| mGoogleApiClient.isConnecting()) {
					mGoogleApiClient.disconnect();
				}
			}

		} else {
			mSimpleFacebook.onActivityResult(this, requestCode, resultCode,
					data);
		}

	}

	public void googleSignupClick(View v) {
		mGoogleApiClient.connect();
	}

	private void PostSignupWithGoogle(Person user) {
		RequestParams params = new RequestParams();
		params.put("name", user.getDisplayName() + "");
		if (user.getGender() == 1) {
			params.put("gender", "female");
		} else {
			params.put("gender", "male");
		}
		params.put("email", Plus.AccountApi.getAccountName(mGoogleApiClient));
		params.put("locale", user.getLanguage() + "");
		params.put("verified", user.isVerified() + "");
		params.put("socialid", user.getId() + "");

		params.put("jsonArray", user.toString());
		params.put("birthday", user.getBirthday() + "");
		params.put("agent", "google");

		ResharyRestClient.post("socialconnect/", params,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							Throwable arg3) {
						// TODO Auto-generated method stub
						disconnectConnections();
						Toast.makeText(
								getApplicationContext(),
								getResources()
										.getString(R.string.network_error),
								Toast.LENGTH_LONG).show();
					}

					@Override
					public void onSuccess(int statusCode, String content) {
						// TODO Auto-generated method stub
						Map<String, String> postResponse = Util
								.newformatResponse(content);
						if (postResponse.containsKey("status")) {
							if (postResponse.get("status").equals("success")) {
								Util.sharedPrefsPutLogin(
										getApplicationContext(), postResponse);
								Util.intentLogin(getApplicationContext());
							}
						} 
					}

				}, this);
	}

	private void PostSignupWithFacebook(Profile user) {
		RequestParams params = new RequestParams();
		if(user.getName() != null){
			params.put("name", user.getName());
		}
		if(user.getGender() != null){
			params.put("gender", user.getGender());
		}
		
		if(user.getEmail() != null){
			params.put("email", user.getEmail());
		}

		if(user.getLocale() != null){
			params.put("locale", user.getLocale());
		}
		
		if(user.getVerified() != null){
			params.put("verified", user.getVerified());
		}

		if(user.getId() != null){
			params.put("socialid", user.getId());
		}
	
		if(user.getTimeZone() != 0){
			params.put("timezone", user.getTimeZone() + "");
		}
		
		if(user.toString() != null){
			params.put("jsonArray", user.toString());
		}
		
		
		// params.put("birthday", user.getProperty("birthday"));
		params.put("agent", "facebook");

		
		ResharyRestClient.post("socialconnect/", params,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							Throwable arg3) {
						// TODO Auto-generated method stub
						disconnectConnections();
						Toast.makeText(
								getApplicationContext(),
								getResources()
										.getString(R.string.network_error),
								Toast.LENGTH_LONG).show();
					}

					@Override
					public void onSuccess(int statusCode, String content) {
						// TODO Auto-generated method stub
						Map<String, String> postResponse = Util
								.newformatResponse(content);
						if (postResponse.containsKey("status")) {
							if (postResponse.get("status").equals("success")) {
								Util.sharedPrefsPutLogin(
										getApplicationContext(), postResponse);
								Util.intentLogin(getApplicationContext());
							}
						}
					}

				}, this);

	}

	private void disconnectConnections() {
		if (mGoogleApiClient.isConnected()) {
			mGoogleApiClient.disconnect();
		}
	}

	public void loginOnClick(View v) {
		Intent login = new Intent(getApplicationContext(), LoginScreen.class);
		startActivity(login);
		overridePendingTransition(R.anim.right_in, R.anim.left_out);

	}

	public void signupOnClick(View v) {
		Intent signup = new Intent(getApplicationContext(), SignupScreen.class);
		startActivity(signup);
		overridePendingTransition(R.anim.right_in, R.anim.left_out);

	}

	public void onConnectionFailed(ConnectionResult result) {
		if (!mIntentInProgress && result.hasResolution()) {
			try {
				mIntentInProgress = true;
				result.startResolutionForResult(this, // your activity
						RC_SIGN_IN);
			} catch (SendIntentException e) {
				mIntentInProgress = false;
				mGoogleApiClient.connect();
			}
		}
	}

	public void onConnected(Bundle connectionHint) {
		if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
			Person currentPerson = Plus.PeopleApi
					.getCurrentPerson(mGoogleApiClient);
			PostSignupWithGoogle(currentPerson);
		}
	}

	@Override
	public void onConnectionSuspended(int arg0) {
		// TODO Auto-generated method stub
		mGoogleApiClient.connect();
	}

	@Override
	public void onResume() {
		super.onResume();
		mSimpleFacebook = SimpleFacebook.getInstance(this);
	}

}
